const app = getApp();
Page({
  data: {
    Questions:[],
    Answers:[],
    competitionId: null,
    currentIndex: 0,
    score: 0, // 保存前端计算的总分数
    answers: Array(20).fill(null), // 记录用户的答案
    timeLeft: 300, // 5分钟倒计时
    formattedTime: '5min0s', // Initial formatted time
    showPreview: false, // 是否显示预览界面
    totalQuestions: 20,
    skipped: Array(20).fill(false), // 标记是否跳过
    previewOpen: false,
    timerInterval: null,
    warningTimeout: null,
    seenQuestions: Array(20).fill(false),
    isPaused: false, // Changed to false to start the timer automatically
    pauseButtonText: '暂停', // Initial button text
    hasSubmitted: false, // 新增一个标志，表示是否已提交
  },

  onLoad(options) {
    const competitionId = options.competitionId;
    this.setData({
      competitionId: competitionId
    });
    this.setData({ formattedTime: this.formatTime(this.data.timeLeft) }); // Initialize formatted time
    this.setData({ seenQuestions: this.data.seenQuestions.map((_, index) => index === this.data.currentIndex ? true : _) });
    this.startTimer();
    this.getQuestions();

  },

  onUnload() {
    this.clearTimer();
  },

  // 格式化时间
  formatTime(seconds) {
    const minutes = Math.floor(seconds / 60);
    const remainingSeconds = seconds % 60;
    return `${minutes}min${remainingSeconds}s`;
  },

  // 计时器
  startTimer() {
    this.data.timerInterval = setInterval(() => {
      let { timeLeft, isPaused, hasSubmitted } = this.data;
      if (!isPaused && !hasSubmitted) { // 只有在未暂停且未提交的情况下才倒计时
        timeLeft--;
        const formattedTime = this.formatTime(timeLeft);
        this.setData({
          timeLeft: timeLeft,
          formattedTime: formattedTime
        });

        if (timeLeft === 60) {
          wx.showToast({ title: "剩余 1 分钟", icon: "none", duration: 5000 });
        }

        if (timeLeft <= 0) {
          this.clearTimer();
          this.autoSubmit();
        }
      }
    }, 1000);
  },

  // 清除计时器
  clearTimer() {
    clearInterval(this.data.timerInterval);
    clearTimeout(this.data.warningTimeout);
  },

  // 切换暂停/继续
  togglePause() {
    this.setData({
      isPaused: !this.data.isPaused,
      pauseButtonText: this.data.isPaused ? '暂停' : '继续',
    }, () => {
      if (!this.data.timerInterval) {
        this.startTimer();
      }
    });
  },

  // 记录用户的答案
  selectOption(e) {
    const { value } = e.detail; // Get the selected value from e.detail
    const { currentIndex, answers } = this.data;
    const newAnswers = [...answers];
    newAnswers[currentIndex] = value;
    this.setData({ answers: newAnswers });
  },

  // 上一题
  previousQuestion() {
    let { currentIndex } = this.data;
    if (currentIndex > 0) {
      this.setData({
        currentIndex: currentIndex - 1,
        seenQuestions: this.data.seenQuestions.map((seen, index) => index === currentIndex - 1 ? true : seen),
      });
    } else {
      wx.showToast({ title: "已经是第一题", icon: "none" });
    }
  },

  // 下一题
  nextQuestion() {
    let { currentIndex, Questions, answers, skipped } = this.data;
    const newSkipped = [...skipped];
    if (!answers[currentIndex]) {
      newSkipped[currentIndex] = true; // 标记跳过
    }
    if (currentIndex < Questions.length - 1) {
      this.setData({
        currentIndex: currentIndex + 1,
        skipped: newSkipped,
        seenQuestions: this.data.seenQuestions.map((seen, index) => index === currentIndex + 1 ? true : seen),
      });
    } else {
      this.submitQuiz();
    }
  },

  // 预览所有题目
  openPreview() {
    this.setData({ previewOpen: true });
  },

  // 关闭预览
  closePreview() {
    this.setData({ previewOpen: false });
  },

  // 跳转到指定题目
  jumpToQuestion(e) {
    this.setData({
      currentIndex: parseInt(e.currentTarget.dataset.index),
      previewOpen: false,
      seenQuestions: this.data.seenQuestions.map((seen, index) => index === parseInt(e.currentTarget.dataset.index) ? true : seen),
    });
  },

  // 提交答案
  submitQuiz() {
    const { answers, Questions, competitionId } = this.data;
    const unanswered = answers.some(answer => answer === null);
    if (unanswered) {
      wx.showToast({ title: "还有题目未完成！", icon: "none" });
      return;
    }

    this.clearTimer();
    this.setData({ hasSubmitted: true });

    let score = 0;
    Questions.forEach((question, index) => {
      const selectedAnswerId = answers[index];
      const correctAnswerOption = question.options.find(option => option.iscorrect === true);
      if (correctAnswerOption && selectedAnswerId == correctAnswerOption.id) {
        score += 5;
      }
    });
    this.setData({ score: score }); // 保存计算出的分数

    const userId = wx.getStorageSync('userId'); // 获取用户 ID

    wx.request({
      url: `${app.globalData.baseUrl}/api/quiz/submit/${competitionId}`, // 修改为接收分数的后端接口
      method: 'POST',
      header: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      data: {
        totalPoint: this.data.score, // 发送计算出的总分数
        wxusersId: userId, // 发送用户 ID
        competitionId: competitionId, // 发送比赛 ID
        submitTime: new Date() // 可选：发送提交时间，后端也可以获取
      },
      success: (res) => {
        console.log('提交分数成功 (后端):', res);
        wx.navigateTo({
          url: `/pages/person/Quiz-index/Quiz-result/Quiz-result?score=${this.data.score}&total=${Questions.length * 10}`
        });
      },
      fail: (err) => {
        console.error('提交分数失败 (后端):', err);
      }
    });
  },

  // 时间到自动提交
  autoSubmit() {
    const { hasSubmitted } = this.data;
    if (hasSubmitted) {
      return;
    }

    const { answers, Questions, competitionId } = this.data;

    this.clearTimer();
    this.setData({ hasSubmitted: true });

    let score = 0;
    Questions.forEach((question, index) => {
      const selectedAnswerId = answers[index];
      const correctAnswerOption = question.options.find(option => option.iscorrect === true);
      if (correctAnswerOption && selectedAnswerId == correctAnswerOption.id) {
        score += 5;
      }
    });
    this.setData({ score: score }); // 保存计算出的分数

    const userId = wx.getStorageSync('userId'); // 获取用户 ID

    wx.showModal({
      title: "时间到",
      content: "时间已到，系统已自动提交你的答案！",
      showCancel: false,
      success: () => {
        wx.request({
          url: `${app.globalData.baseUrl}/api/quiz/submit/${competitionId}`, // 修改为接收分数的后端接口
          method: 'POST',
          header: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + wx.getStorageSync('token')
          },
          data: {
            totalPoint: this.data.score, // 发送计算出的总分数
            wxusersId: userId, // 发送用户 ID
            competitionId: competitionId, // 发送比赛 ID
            submitTime: new Date() // 可选：发送提交时间，后端也可以获取
          },
          success: (res) => {
            console.log('自动提交分数成功 (后端):', res);
            wx.navigateTo({
              url: `/pages/person/Quiz-index/Quiz-result/Quiz-result?score=${this.data.score}&total=${Questions.length * 10}`
            });
          },
          fail: (err) => {
            console.error('自动提交分数失败 (后端):', err);
          }
        });
      }
    });
  },
  getQuestions() {
    const competitionId = this.data.competitionId;
    wx.request({
      url: `${app.globalData.baseUrl}/api/quiz/questions/${competitionId}`,
      method: 'GET',
      header: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + wx.getStorageSync('token'),
        'userId': wx.getStorage('userId')
      },
      success: (res) => {
        console.log('getQuestions response:', res); // 添加这行
        if (res.statusCode === 200) {
          const questions = res.data.data;
          console.log(res.data.data)
          this.setData({
            Questions: questions,
            totalQuestions: questions.length // 更新总题目数量
          });
          this.setData({ answers: Array(questions.length).fill(null) }); // 初始化答案数组
          this.setData({ skipped: Array(questions.length).fill(false) }); // 初始化跳过数组
          this.setData({ seenQuestions: Array(questions.length).fill(false).map((_, index) => index === this.data.currentIndex ? true : _) }); // 初始化查看状态
        } else {
          console.error('请求失败，状态码:', res.statusCode);
        }
      },
      fail: (err) => {
        console.log('请求失败:', err);
      }
    })
  },
 
});